package hzk.codex2016.list;

public class LinkedLists_merge {

	/**
	 * https://leetcode.com/problems/merge-two-sorted-lists/
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	ListNode merge2lists(ListNode a, ListNode b) {

		ListNode fakeHead = new ListNode(0);
		ListNode pre = fakeHead;

		while (a != null && b != null) {
			if (a.val > b.val) {
				pre = pre.next = b;
				b = b.next;
			} else {
				pre = pre.next = a;
				a = a.next;
			}

		}
		if (a != null)
			pre.next = a;
		if (b != null)
			pre.next = b;
		return fakeHead.next;

	}
	
	
	

	static ListNode ll(int... vals) {
		return ListNode.asList(vals);
	}

	public static void main(String[] args) {
		LinkedLists_merge p = new LinkedLists_merge();
		System.out.println(
				p.merge2lists(ll(1, 3, 5, 7, 9, 11, 14, 17, 20, 22), ll(2, 4, 6, 8, 10, 12, 13, 18, 23, 26, 30)));
		System.out.println(p.merge2lists(ll(), ll()));
		System.out.println(p.merge2lists(ll(), ll(1)));
		System.out.println(p.merge2lists(ll(3), ll()));
		System.out.println(p.merge2lists(ll(2), ll(4,5,6)));
	}
}
